<template>
  <div class="content-goods-publish">
    <a-form ref="baseInfoFormRules" :model="baseInfoForm">
      <div class="base-info-item">
        <h4>基本信息</h4>
        <div class="form-item-view">
          <a-form-item label="商品分类">
            <span class="goods-category-name">{{
              baseInfoForm.categoryName[0]
            }}</span>
            <span> &gt; {{ baseInfoForm.categoryName[1] }}</span>
            <span> &gt; {{ baseInfoForm.categoryName[2] }}</span>
          </a-form-item>
          <a-form-item field="goodsName" label="商品名称" :rules="[REQUIRED]">
            <a-input
              v-model="baseInfoForm.goodsName"
              placeholder="请输入商品名称"
            />
          </a-form-item>
          <a-form-item
            field="price"
            label="商品价格"
            :rules="[REQUIRED, MONEY]"
          >
            <a-input
              v-model="baseInfoForm.price"
              placeholder="请输入商品价格"
            />
          </a-form-item>
          <a-form-item
            field="sellingPoint"
            label="商品卖点"
            :rules="[REQUIRED]"
          >
            <a-textarea
              v-model="baseInfoForm.sellingPoint"
              placeholder="请输入商品卖点"
              allow-clear
              auto-size
            />
          </a-form-item>
          <a-form-item field="brandId" label="商品品牌">
            <a-select
              v-model="baseInfoForm.brandId"
              :style="{ width: '320px' }"
              allow-clear
              placeholder="请选择商品品牌"
            >
              <a-option
                v-for="item in brandList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></a-option>
            </a-select>
          </a-form-item>
        </div>
      </div>
      <div class="base-info-item">
        <h4>商品交易信息</h4>
        <a-form-item field="goodsUnit" label="计量单位">
          <a-select
            v-model="baseInfoForm.goodsUnit"
            :style="{ width: '320px' }"
            placeholder="请选择计量单位"
          >
            <a-option
              v-for="(item, index) in goodsUnitList"
              :key="index"
              :value="item"
              >{{ item }}</a-option
            >
          </a-select>
        </a-form-item>
        <a-form-item field="salesModel" label="销售模式">
          <a-radio-group
            v-if="baseInfoForm.goodsType != 'VIRTUAL_GOODS'"
            v-model="baseInfoForm.salesModel"
            type="button"
            @change="renderTableData(skuTableData)"
          >
            <a-radio value="RETAIL">零售型</a-radio>
            <a-radio value="WHOLESALE">批发型</a-radio>
          </a-radio-group>
          <a-radio-group v-else v-model="baseInfoForm.salesModel" type="button">
            <a-radio value="RETAIL">虚拟型</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          v-if="baseInfoForm.salesModel == 'WHOLESALE'"
          class="form-item-view-el"
          label="销售规则"
          field="wholesaleRule"
        >
          <div style="display: flex">
            <div>
              <a-table
                :columns="wholesaleColumns"
                :data="wholesaleData"
                :pagination="false"
                :bordered="{ cell: true }"
              >
                <template #wholesaleNum="{ rowIndex }">
                  <a-input
                    v-model="wholesaleData[rowIndex].num"
                    clearable
                    placeholder="请输入数量"
                    @on-blur="checkWholesaleNum(rowIndex)"
                  >
                    <template #append>
                      {{ baseInfoForm.goodsUnit || '' }}
                    </template>
                  </a-input>
                </template>
                <template #wholesalePrice="{ rowIndex }">
                  <div
                    style="
                      display: flex;
                      justify-content: space-between;
                      align-items: center;
                    "
                  >
                    <a-input
                      v-model="wholesaleData[rowIndex].price"
                      clearable
                      placeholder="请输入单价"
                      @on-blur="checkWholesalePrice(rowIndex)"
                    >
                      <template #append>元</template>
                    </a-input>
                    <a-button
                      v-if="rowIndex > 0"
                      style="margin-left: 5px"
                      @click="handleDeleteWholesaleData(rowIndex)"
                      >删除</a-button
                    >
                  </div>
                </template>
              </a-table>
              <a-button
                v-if="wholesaleData.length < 3"
                style="margin-top: 10px"
                @click="handleAddWholesaleData"
              >
                <template #icon><icon-plus /></template>
                添加价格区间
              </a-button>
            </div>
            <div style="padding-left: 5%">
              <a-table
                :columns="wholesalePreviewColumns"
                :data="wholesaleData"
                :pagination="false"
              >
                <template #rule="{ rowIndex }">
                  <div>{{
                    `当商品购买数量 ≥ ${wholesaleData[rowIndex].num}时，售价为 ￥${wholesaleData[rowIndex].price}/${baseInfoForm.goodsUnit}`
                  }}</div>
                </template>
              </a-table>
            </div>
          </div>
        </a-form-item>
      </div>
      <div class="base-info-item">
        <h4>商品规格及图片</h4>
        <a-form-item class="required" field="goodsGalleryList" label="商品图片">
          <div>
            <div
              v-if="
                baseInfoForm.goodsGalleryList &&
                baseInfoForm.goodsGalleryList.length
              "
              style="
                width: 100%;
                margin-bottom: 5px;
                display: flex;
                flex-wrap: wrap;
              "
            >
              <a-space
                v-for="(item, index) in baseInfoForm.goodsGalleryList"
                :key="index"
              >
                <dnd
                  :index="index"
                  :move-card="moveCard"
                  dnd-key="goodsGalleryList"
                >
                  <a-image
                    style="margin: 0 5px 5px 0"
                    width="150"
                    height="150"
                    :src="item"
                  >
                    <template #extra>
                      <div class="actions">
                        <span class="action" @click="look(item)"
                          ><icon-eye
                        /></span>
                        <span
                          class="action"
                          @click="handleRemoveIntro(index, 'goodsGalleryList')"
                          ><icon-delete
                        /></span>
                      </div>
                    </template>
                  </a-image>
                </dnd>
              </a-space>
            </div>
            <!--<upload-image :clear="true" @change="insertImage($event,'goodsGalleryList')" />-->
            <div style="display: flex; justify-content: flex-start"
              ><a-button @click="handleClickOssManages('goods')"
                >上传图片</a-button
              >
            </div>
          </div>
        </a-form-item>
        <!-- accept -->
        <a-form-item field="post" label="上传视频">
          <div class="goods-video" min-w-200px text-left>
            <div v-if="baseInfoForm.goodsVideo">
              <div>
                <video controls class="video" :src="baseInfoForm.goodsVideo" />
              </div>
            </div>
            <PickUpload
              v-if="!baseInfoForm.goodsVideo"
              :size="20"
              :access-token="accessToken"
              :limit="1"
              :api="uploadFile"
              accept="video/*"
              :file-format="['mp4']"
              @on-success="handleSuccessVideo($event)"
            />
            <a-button v-else ml-10px @click="baseInfoForm.goodsVideo = ''">
              清除视频
            </a-button>
          </div>
        </a-form-item>
        <div class="layout" style="width: 100%">
          <a-collapse :bordered="false" :active-key="openPanel">
            <a-collapse-item :key="1" header="自定义规格项">
              <div>
                <a-form :model="form">
                  <div
                    v-for="(item, $index) in skuInfo"
                    :key="$index"
                    class="sku-item-content"
                  >
                    <a-card :bordered="true" class="ivu-card-body">
                      <template #extra
                        ><a-button @click="handleCloseSkuItem($index, item)"
                          >删除规格</a-button
                        ></template
                      >
                      <div>
                        <a-form-item
                          class="sku-item-content-val flex"
                          label="规格名"
                        >
                          <a-auto-complete
                            v-model="item.name"
                            :data="skuData"
                            :style="{ width: '150px' }"
                            placeholder="请输入规格名称"
                            @focus="changeSkuItem(item.name)"
                            @change="editSkuItem(item.name, $index, item)"
                          />
                        </a-form-item>
                      </div>
                      <div class="flex sku-val">
                        <a-form :model="item" class="flex">
                          <a-form-item
                            v-for="(val, index) in item.spec_values"
                            :key="index"
                            class="sku-item-content-val flex"
                            label="规格项"
                          >
                            <a-auto-complete
                              ref="input"
                              v-model="val.value"
                              :data="skuVal"
                              :style="{ width: '150px' }"
                              placeholder="请输入规格项"
                              @blur="checkSkuVal(val, index, item)"
                              @focus="changeSkuVals(val, item.name)"
                              @change="skuValueChange(val, index, item)"
                            />
                            <a-button
                              style="margin-left: 10px"
                              @click="handleCloseSkuValue(val, index, item)"
                              >删除</a-button
                            >
                          </a-form-item>
                        </a-form>
                      </div>
                      <div
                        ><a-button @click="addSpec($index, item)"
                          >添加规格值</a-button
                        ></div
                      >
                    </a-card>
                  </div>
                </a-form>
                <a-button class="add-sku-btn" type="primary" @click="addSkuItem"
                  >添加规格项</a-button
                >
                &nbsp; &nbsp;
                <a-button
                  class="add-sku-btn"
                  type="primary"
                  status="danger"
                  @click="handleClearSku"
                  >清空规格项</a-button
                >
              </div>
            </a-collapse-item>
            <a-collapse-item :key="2" header="规格详细">
              <div>
                <a-table
                  :columns="skuTableColumn"
                  :data="skuTableData"
                  class="mt_10"
                  style="
                    width: 100%;
                    .ivu-table-overflowX {
                      overflow-x: hidden;
                    }
                  "
                  :pagination="false"
                >
                  <template #sn="{ record, rowIndex }">
                    <a-input
                      v-model="record.sn"
                      clearable
                      placeholder="请输入"
                      @change="updateSkuTable(record, rowIndex, 'sn')"
                    />
                  </template>
                  <template
                    v-if="baseInfoForm.goodsType !== 'VIRTUAL_GOODS'"
                    #weight="{ record, rowIndex }"
                  >
                    <a-input-number
                      v-model="record.weight"
                      clearable
                      placeholder="请输入"
                      :min="0.0001"
                      :max="9999999"
                      hide-button
                      @change="updateSkuTable(record, rowIndex, 'weight')"
                    >
                      <template #append> kg </template>
                    </a-input-number>
                  </template>
                  <template #quantity="{ record, rowIndex }">
                    <a-input-number
                      v-model="record.quantity"
                      clearable
                      placeholder="请输入"
                      :min="0"
                      :max="9999999"
                      hide-button
                      :precision="0"
                      @change="updateSkuTable(record, rowIndex, 'quantity')"
                    >
                      <template #append>
                        {{ baseInfoForm.goodsUnit || '' }}
                      </template>
                    </a-input-number>
                  </template>
                  <template #cost="{ record, rowIndex }">
                    <a-input-number
                      v-model="record.cost"
                      clearable
                      placeholder="请输入"
                      :min="0"
                      :max="9999999"
                      hide-button
                      @change="updateSkuTable(record, rowIndex, 'cost')"
                    >
                      <template #append> 元 </template>
                    </a-input-number>
                  </template>
                  <template #price="{ record, rowIndex }">
                    <a-input-number
                      v-model="record.price"
                      clearable
                      placeholder="请输入"
                      :min="0"
                      :max="9999999"
                      hide-button
                      @change="updateSkuTable(record, rowIndex, 'price')"
                    >
                      <template #append> 元 </template>
                    </a-input-number>
                  </template>
                  <template #wholePrice0="{}">
                    <a-input
                      v-if="wholesaleData[0]"
                      v-model="wholesaleData[0].price"
                      clearable
                      disabled
                    >
                      <template #append> 元 </template>
                    </a-input>
                  </template>
                  <template #wholePrice1="{}">
                    <a-input
                      v-if="wholesaleData[1]"
                      v-model="wholesaleData[1].price"
                      clearable
                      disabled
                    >
                      <template #append> 元 </template>
                    </a-input>
                  </template>
                  <template #wholePrice2="{}">
                    <a-input
                      v-if="wholesaleData[2]"
                      v-model="wholesaleData[2].price"
                      clearable
                      disabled
                    >
                      <template #append> 元 </template>
                    </a-input>
                  </template>
                  <template #images="{ record, rowIndex }">
                    <div @mouseover="mouseOver(record)">
                      <a-button type="primary" @click="editSkuPicture(record)"
                        >编辑图片!</a-button
                      >
                    </div>
                    <a-modal
                      v-model:visible="showSkuPicture"
                      ok-text="结束编辑"
                      title="编辑图片"
                      @ok="updateSkuPicture(rowIndex)"
                    >
                      <div>
                        <div
                          style="
                            width: 100%;
                            margin-bottom: 5px;
                            display: flex;
                            flex-wrap: wrap;
                          "
                        >
                          <a-space
                            v-for="(item, index) in selectedSku.images"
                            :key="index"
                          >
                            <dnd
                              :index="index"
                              :move-card="moveCardSku"
                              dnd-key="images"
                            >
                              <a-image
                                style="margin: 0 5px 5px 0"
                                width="80"
                                height="80"
                                :src="item"
                              >
                                <template #extra>
                                  <div>
                                    <span class="action" @click="look(item)"
                                      ><icon-eye
                                    /></span>
                                    <span
                                      class="action"
                                      @click="
                                        handleRemoveIntro(index, 'selectedSku')
                                      "
                                      ><icon-delete
                                    /></span>
                                  </div>
                                </template>
                              </a-image>
                            </dnd>
                          </a-space>
                          <div
                            style="display: flex; justify-content: flex-start"
                          >
                            <div
                              class="goods-sku-images-upload"
                              @click="handleClickOssManages('sku')"
                              ><icon-plus
                            /></div>
                          </div>
                        </div>
                        <!-- <div class="import-oss" @click="importOSS">从资源库中导入</div> -->
                        <!--<a-upload  list-type="picture-card" :action="uploadFile"  :headers="{token:accessToken}"-->
                        <!--:onSuccess="handleSucces" :onError="handleError"  image-preview-->
                        <!--:file-list="selectedSku.images"     @before-remove="handleRemove"/>-->
                      </div>
                    </a-modal>
                  </template>
                </a-table>
              </div>
            </a-collapse-item>
          </a-collapse>
        </div>
      </div>
      <div class="base-info-item">
        <h4 v-if="showContent">规格描述内容</h4>
        <div v-if="showContent" class="form-item-view">
          <a-form-item :label="contentImage">
            <div v-for="(item, index) in listImages.images" :key="index">
              <!--  @click="getImages(item.url)" -->
              <!--<a-image width="100" height="100" style="margin-left: 5px;" :src="item.url" />-->
              <a-image
                width="100"
                height="100"
                style="margin-left: 5px"
                :src="item"
              />
            </div>
          </a-form-item>
        </div>
      </div>
      <div class="base-info-item">
        <h4>商品详情描述</h4>
        <a-form-item label="店内分类" field="shopCategory">
          <a-tree
            v-model:selected-keys="baseInfoForm.storeCategoryPath"
            v-model:checked-keys="baseInfoForm.storeCategoryPath"
            :checkable="true"
            :data="shopCategory"
            :check-strictly="false"
            :field-names="{ key: 'id', title: 'labelName' }"
            show-checkbox
            style="text-align: left"
            @check="changeSelect"
          ></a-tree>
        </a-form-item>
        <a-form-item class="form-item-view-el" label="PC商品描述" field="intro">
          <div>
            <div
              v-if="baseInfoForm.intro && baseInfoForm.intro.length"
              style="
                width: 100%;
                margin-bottom: 5px;
                display: flex;
                flex-wrap: wrap;
              "
            >
              <a-space v-for="(item, index) in baseInfoForm.intro" :key="index">
                <dnd :index="index" :move-card="moveCard" dnd-key="intro">
                  <a-image
                    style="margin: 0 5px 5px 0"
                    width="150"
                    height="150"
                    :src="item"
                  >
                    <template #extra>
                      <div class="actions">
                        <span class="action" @click="look(item)"
                          ><icon-eye
                        /></span>
                        <span
                          class="action"
                          @click="handleRemoveIntro(index, 'intro')"
                          ><icon-delete
                        /></span>
                      </div>
                    </template>
                  </a-image>
                </dnd>
              </a-space>
            </div>
            <!--<upload-image-->
            <!--:clear="true"-->
            <!--@change="insertImage($event, 'intro')"-->
            <!--/>-->
            <div style="display: flex; justify-content: flex-start">
              <a-button @click="handleClickOssManages('intro')">
                上传图片
              </a-button>
            </div>
          </div>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="promiseIntroEditor"
            >将PC商品描述同步到移动端描述</a-button
          >
        </a-form-item>
        <a-form-item
          class="form-item-view-el"
          label="移动端描述"
          field="mobileIntro"
        >
          <div class="mobile-intro">
            <div class="mobile-effect">
              <div class="title">页面预览</div>
              <div
                v-if="
                  baseInfoForm.mobileIntro && baseInfoForm.mobileIntro.length
                "
                class="content"
              >
                <div>
                  <a-space
                    v-for="(item, index) in baseInfoForm.mobileIntro"
                    :key="index"
                  >
                    <dnd
                      :index="index"
                      :move-card="moveCard"
                      dnd-key="mobileIntro"
                    >
                      <a-image width="308" :src="item"></a-image>
                    </dnd>
                  </a-space>
                </div>
              </div>
              <div v-else class="content text"
                >选择右侧上传按钮进行商品详情装修</div
              >
            </div>
            <div>
              <div
                v-if="
                  baseInfoForm.mobileIntro && baseInfoForm.mobileIntro.length
                "
                style="
                  width: 100%;
                  margin-bottom: 5px;
                  display: flex;
                  flex-wrap: wrap;
                "
              >
                <a-space
                  v-for="(item, index) in baseInfoForm.mobileIntro"
                  :key="index"
                >
                  <dnd
                    :index="index"
                    :move-card="moveCard"
                    dnd-key="mobileIntro"
                  >
                    <a-image
                      style="margin: 0 5px 5px 0"
                      width="150"
                      height="150"
                      :src="item"
                    >
                      <template #extra>
                        <div class="actions">
                          <span class="action" @click="look(item)"
                            ><icon-eye
                          /></span>
                          <span
                            class="action"
                            @click="handleRemoveIntro(index, 'mobileIntro')"
                            ><icon-delete
                          /></span>
                        </div>
                      </template>
                    </a-image>
                  </dnd>
                </a-space>
              </div>
              <!--<upload-image-->
              <!--:clear="true"-->
              <!--@change="insertImage($event, 'mobileIntro')"-->
              <!--/>-->
              <a-button @click="handleClickOssManages('mobileIntro')">
                上传图片
              </a-button>
            </div>
          </div>
        </a-form-item>
      </div>
      <div v-if="baseInfoForm.goodsType != 'VIRTUAL_GOODS'">
        <div class="base-info-item">
          <h4>商品物流信息</h4>
          <a-form-item label="物流模板" field="templateId" :rules="[REQUIRED]">
            <a-select
              v-model="baseInfoForm.templateId"
              :style="{ width: '320px' }"
              placeholder="请选择物流模板"
            >
              <a-option
                v-for="item in logisticsTemplate"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></a-option>
            </a-select>
          </a-form-item>
          <a-form-item
            v-if="baseInfoForm.salesModel == 'WHOLESALE'"
            class="form-item-view-el"
            label="商品重量"
            field="weight"
          >
            <a-input v-model="baseInfoForm.weight" placeholder="请输入商品重量">
              <template #append> kg </template>
            </a-input>
          </a-form-item>
        </div>
        <div class="base-info-item">
          <h4>其他信息</h4>
          <a-form-item label="商品发布" field="release">
            <a-radio-group v-model="baseInfoForm.release" type="button">
              <a-radio :value="1">立即发布</a-radio>
              <a-radio :value="0">放入仓库</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="商品推荐" field="recommend">
            <a-radio-group v-model="baseInfoForm.recommend" type="button">
              <a-radio :value="1">推荐</a-radio>
              <a-radio :value="0">不推荐</a-radio>
            </a-radio-group>
          </a-form-item>
        </div>
      </div>
      <div class="form-item-view-bottom">
        <a-collapse
          v-for="(paramsGroup, groupIndex) in goodsParams"
          :key="paramsGroup.groupName"
          :title="paramsGroup.groupName"
          class="mb_10"
          style="text-align: left"
          :active-key="paramsPanel"
        >
          <a-collapse-item
            v-if="paramsGroup.groupName"
            :key="paramsGroup.groupName"
            :header="paramsGroup.groupName"
          >
            <div>
              <a-form-item
                v-for="(params, paramsIndex) in paramsGroup.params"
                :key="paramsIndex"
                :label="`${params.paramName}：`"
              >
                <a-select
                  v-model="params.paramValue"
                  clearable
                  placeholder="请选择"
                  style="width: 200px"
                  @change="
                    selectParams(
                      paramsGroup,
                      groupIndex,
                      params,
                      paramsIndex,
                      params.paramValue
                    )
                  "
                >
                  <a-option
                    v-for="option in params.options.split(',')"
                    :key="option"
                    :label="option"
                    :value="option"
                  ></a-option>
                </a-select>
              </a-form-item>
            </div>
          </a-collapse-item>
        </a-collapse>
      </div>
    </a-form>
    <!-- 底部按钮 -->
    <div class="footer">
      <!--<a-button-group>-->
      <a-button type="primary" @click="pre"><icon-left />上一步</a-button>
      <a-button type="primary" @click="save"> 保存商品 <icon-right /></a-button>
      <!--</a-button-group>-->

      <!--<a-button type="primary" @click="pre">上一步</a-button>-->
      <!--<a-button type="primary" @click="save">保存商品</a-button>-->
      <!--<a-button type="primary" @click="saveToDraft">保存为模版</a-button>-->
    </div>
    <a-modal
      v-model:visible="showOssManager"
      :width="920"
      title="oss资源管理"
      @ok="handleOss"
      @cancel="handleCancel"
    >
      <ossManage :close-model="handleOss" @selected="changOssImage"></ossManage>
    </a-modal>
    <!--预览图片-->
    <a-modal v-model:visible="picVisible" title="查看图片" draggable>
      <a-image :src="picFile.url" width="100%" alt="无效的图片链接"></a-image>
      <!--<template #footer>-->
      <!--<span>文件类型：{{ file.fileType }} 文件大小：{{ file.msize }}</span>-->
      <!--</template>-->
    </a-modal>
    <!--上传图片弹框-->
    <a-modal
      v-model:visible="showOssManages"
      :width="966"
      title="选择图片"
      :body-style="{ paddingTop: '0px', paddingBottom: '0px' }"
      @ok="ossManagesOk"
      @cancel="ossManagesCancel"
    >
      <ossManages
        :initialize="showOssManages"
        @selected="ossManagesSelected"
      ></ossManages>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import uploadFile from '@/api/common';
  import {
    createGoods,
    editGoods,
    getCategoryBrandListDataSeller,
    getCategoryParamsListDataSeller,
    getDraftGoodsDetail,
    getGoods,
    getGoodsSpecInfoSeller,
    getGoodsUnitList,
    getLabelData,
    getShipTemplate,
    saveDraftGoods,
  } from '@/api/goods';
  import ossManage from '@/components/oss-manage/index.vue';
  import ossManages from '@/components/oss-manages/index.vue';
  import uploadImage from '@/components/upload-image/index.vue';
  import useCurrentInstance from '@/hooks/useCurrentInstance';
  import { cloneObj, money } from '@/utils/filters';
  import store from '@/utils/storage';
  import { REQUIRED, MONEY } from '@/utils/validator';
  import { Message, Notification } from '@arco-design/web-vue';
  import { FormInstance } from '@arco-design/web-vue/es/form';
  import { inject, nextTick, onMounted, ref } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import dnd from './dnd.vue';
  import { baseInfoFormRule } from './interface';
  import { PickUpload } from '@pickmall/ui-v3-components';
  const emit: any = defineEmits<{
    (e: 'preChange', val: any, type: string): void;
  }>();
  const props = defineProps({
    firstData: {
      type: Object,
      default: () => {
        return {};
      },
    },
  });
  const baseInfoFormRules = ref<FormInstance>();
  const activestep = inject('activestep') as any;
  const showOssManager = ref<boolean>(false); // oss弹框
  const router = useRouter();
  const route = useRoute();
  // 获取modal
  const modal = useCurrentInstance().globalProperties?.$modal;
  const fileFormat = ref<Array<string>>(['jpg', 'jpeg', 'png', 'gif', 'bmp']);
  const categoryId = ref<any>('');
  // 携带toekn
  const accessToken = ref<any>(store.getAccessToken());
  const showSkuPicture = ref<boolean>(false); // 展示sku图片
  const goodsId = ref<any>(''); // 商品id
  const shopCategory = ref<Array<any>>([]); // 店内分类列表
  const showContent = ref<boolean>(false);
  const contentImage = ref<any>('');
  const listImages = ref<any>([]);
  const openPanel = ref<Array<any>>([1, 2]);
  const skuInfo = ref([]) as any; // 提交的规格数据
  const skuTableColumn = ref<Array<any>>([]); // 规格表格头
  const skuTableData = ref([]) as any; // 规格表格数据
  const skuData = ref<Array<any>>([]); // 默认的规格参数
  const skuVal = ref<Array<any>>([]); // 某一项规格名下的规格值
  const skuVals = ref<Array<any>>([]); // 默认的规格值
  const currentSkuVal = ref<any>('');
  const currentSkuItem = ref<any>({});
  const form = ref<any>({});
  const validateError = ref<Array<any>>([]); // 储存未通过校验得单元格位置
  const validatatxt = ref<any>(''); // 固定列校验提示内容
  // const previewPicture = ref("") // 预览图片路径
  const selectedSku = ref<any>({}); // 选择的sku
  const logisticsTemplate = ref<Array<any>>([]); // 物流模板
  const paramsPanel = ref([]) as any; // 参数panel展示
  const goodsParams = ref([]) as any;
  const goodsFileList = ref<any>();
  const wholesaleData = ref<Array<any>>([
    {
      num: '' || 0,
      price: '' || 0,
      goodsId: '',
    },
  ]);
  const wholesaleColumns = ref<Array<any>>([
    {
      title: '购买数量',
      dataIndex: 'num',
      slotName: 'wholesaleNum',
      width: 200,
    },
    {
      title: '商品单价',
      dataIndex: 'price',
      slotName: 'wholesalePrice',
      width: 200,
    },
  ]);
  const wholesalePreviewColumns = ref<Array<any>>([
    {
      title: '销售规则',
      dataIndex: 'rule',
      slotName: 'rule',
      width: 300,
    },
  ]);
  const ignoreColumn = ref<Array<any>>([
    'index',
    '_rowKey',
    'sn',
    'cost',
    'price',
    'weight',
    'quantity',
    'specId',
    'specValueId',
  ]);
  const lastEditSkuValue = ref<any>('');
  const skuIndex = ref<number>(0);
  const brandList = ref<any>([{ id: '', name: '' }]); // 品牌列表
  const goodsUnitList = ref<Array<any>>([]); // 商品单位列表
  const params = ref<any>({
    pageNumber: 1,
    pageSize: 1000,
  });
  const baseInfoForm = ref<baseInfoFormRule>({
    salesModel: 'RETAIL',
    goodsGalleryFiles: [], // 商品相册列表
    release: 1, // 是否立即发布 true 立即发布 false 放入仓库
    recommend: 1, // 是否为推荐商品
    storeCategoryPath: [], // 店铺分类
    brandId: null,
    goodsUnit: '个', // 计量单位
    goodsType: '', // 商品类型
    categoryPath: '', // 分类路径
    sellingPoint: null, // 商品卖点
    intro: [], // 商品详情
    mobileIntro: [],
    updateSku: true,
    regeneratorSkuFlag: false, // 是否重新生成sku
    templateId: null, // 物流模板id
    goodsParamsDTOList: [], // 参数组
    categoryName: [], // 商品分类中文名
    goodsVideo: '',
    goodsGalleryList: [],
  });
  const picVisible = ref(false); // 图片的modal
  const picFile = ref({ url: '' }); // 文件数据

  const showOssManages = ref(false); // 上传图片弹框
  const ossManagesType = ref(); // 上传图片类型 goods商品图片，sku商品规格图片
  const ossManagesList = ref([]);

  // 视频上传成功
  function handleSuccessVideo(file: any) {
    baseInfoForm.value.goodsVideo = file;
  }
  const moveCard = (dragIndex: number, hoverIndex: number, key: string) => {
    const item = baseInfoForm.value[key][dragIndex];
    baseInfoForm.value[key].splice(dragIndex, 1);
    baseInfoForm.value[key].splice(hoverIndex, 0, item);
  };
  const moveCardSku = (dragIndex: number, hoverIndex: number) => {
    const item = selectedSku.value.images[dragIndex];
    selectedSku.value.images.splice(dragIndex, 1);
    selectedSku.value.images.splice(hoverIndex, 0, item);
  };

  // 点击上传图片按钮
  const handleClickOssManages = (type: any) => {
    showOssManages.value = true;
    ossManagesType.value = type;
  };
  // 上传图片弹框确认
  const ossManagesOk = () => {
    showOssManages.value = false;
    if (ossManagesType.value === 'goods') {
      // baseInfoForm.value.goodsGalleryList = [];
      ossManagesList.value.forEach((item: any) => {
        baseInfoForm.value.goodsGalleryList.push(item.url);
      });
    } else if (ossManagesType.value === 'sku') {
      // Message.success('上传成功');
      ossManagesList.value.forEach((item: any) => {
        selectedSku.value.images.push(item.url);
      });
    } else if (ossManagesType.value === 'intro') {
      // baseInfoForm.value.intro = [];
      ossManagesList.value.forEach((item: any) => {
        baseInfoForm.value.intro.push(item.url);
      });
    } else if (ossManagesType.value === 'mobileIntro') {
      ossManagesList.value.forEach((item: any) => {
        baseInfoForm.value.mobileIntro.push(item.url);
      });
    }
  };
  // 从子组件获取选择的图片
  const ossManagesSelected = (value: any) => {
    ossManagesList.value = value;
  };
  // 上传图片弹框取消
  const ossManagesCancel = () => {
    showOssManages.value = false;
  };

  // 查询商品品牌列表
  const getGoodsBrandList = () => {
    getCategoryBrandListDataSeller(categoryId.value).then((res) => {
      brandList.value = res;
    });
  };
  // 获取商品单位
  const goodsUnit = () => {
    getGoodsUnitList(params).then((res) => {
      if (res.data.success) {
        goodsUnitList.value.push(
          ...res.data.result.records.map((i: any) => i.name)
        );
      }
    });
  };
  // 图片上传会成功回调
  const handleSuccessGoodsPicture = (res: any) => {
    if (res.response.success) {
      Message.success('上传成功');
      res.url = res.response.result;
      baseInfoForm.value.goodsGalleryFiles.push(res);
      baseInfoForm.value.goodsGalleryList.push(res.response.result);
    }
  };
  const handleSucces = (file: any) => {
    if (file.response.success) {
      Message.success('上传成功');
      if (file.response) {
        file.url = file.response.result;
        if (selectedSku.value.images) {
          selectedSku.value.images.push({ url: file });
        } else {
          selectedSku.value.images = [{ url: file }];
        }
        // previewPicture.value = file.url;
      }
    }
  };
  // 上传前校验
  const handleBeforeUploadGoodsPicture = (file: any) => {
    return new Promise((resolve, reject) => {
      if (
        !fileFormat.value.includes(
          file.name.split('.')[file.name.split('.').length - 1]
        )
      ) {
        reject(new Error('上传失败'));
        Message.error(` 请选择 .jpg .jpeg .png .gif .bmp格式文件`);
      } else if (Number((file.size / 1024).toFixed(0)) > 1024) {
        reject(new Error('上传失败'));
        Message.error(`所选文件大小过大, 不得超过1M`);
      } else {
        resolve(true);
      }
    });
  };
  // 图片上传失败
  const handleError = () => {
    Message.error('上传失败');
  };
  // 插入图片
  const insertImage = (images: any, type: any) => {
    baseInfoForm.value[type] = images;
    if (type === 'goodsGalleryList') {
      // 商品图片
    }
  };
  // 查看
  const look = (v: any) => {
    picFile.value.url = v;
    // picFile.value.msize = `${((v.fileSize * 1.0) / (1024 * 1024)).toFixed(2)}MB`;
    picVisible.value = true;
  };
  // 移除图片
  const handleRemoveIntro = (index: number | string, type: string) => {
    if (type === 'selectedSku') {
      selectedSku.value.images.splice(index, 1);
    } else {
      baseInfoForm.value[type].splice(index, 1);
    }
  };
  // 移除sku图片
  const handleRemove = (item: any) => {
    selectedSku.value.images = selectedSku.value.images.filter(
      (i: any) => i.url !== item.url
    );
    // if (selectedSku.value.images.length > 0 && index === 0) {
    //   previewPicture.value = selectedSku.value.images[0].url;
    // } else if (selectedSku.value.images.length < 0) {
    //   previewPicture.value = "";
    // }
  };
  // 迭代属性，形成表格 ； result 渲染的数据 ； array spec数据
  const specIterator = (result: any, spec: any, skus: any) => {
    let table = result;
    if (spec.length > 0) {
      // 清除当前循环的分组
      const cloneTemp = cloneObj(spec) as any;
      cloneTemp.shift();
      spec[0].spec_values.forEach((specItem: any) => {
        const index = skuIndex.value;
        if (table[index]) {
          table[index][spec[0].name] = specItem.value;
        } else if (skus && skus[index] && specItem.value !== '') {
          const obj = {
            ...skus[index],
            id: skus[index].id,
            sn: skus[index].sn,
            quantity: skus[index].quantity,
            cost: skus[index].cost,
            price: skus[index].price,
            [spec[0].name]: specItem.value,
            images:
              skus[index].images || baseInfoForm.value.goodsGalleryFiles || [],
          };
          if (specItem.value !== '') {
            obj.id = skus[index].id;
          }
          if (skus[index].weight !== '') {
            obj.weight = skus[index].weight;
          }
          table.push(obj);
        } else {
          table.push({
            [spec[0].name]: specItem.value,
            images: baseInfoForm.value.goodsGalleryFiles || [],
          });
        }
        table = specIterator(table, cloneTemp, skus);
      });
    } else {
      skuIndex.value += 1;
    }
    return table;
  };
  // 渲染table所需要的column 和 data
  const renderTableData = (skus: any) => {
    skuTableColumn.value = [];
    const pushData = [] as any;
    // 渲染头部
    skuInfo.value.forEach((sku: any) => {
      // 列名称
      const columnName = sku.name;
      pushData.push({ title: columnName, dataIndex: columnName });
    });
    // 有成本价和价格的情况
    if (baseInfoForm.value.salesModel !== 'WHOLESALE') {
      pushData.push(
        { title: '成本价', slotName: 'cost' },
        { title: '价格', slotName: 'price' }
      );
    }
    if (baseInfoForm.value.salesModel === 'WHOLESALE' && wholesaleData.value) {
      wholesaleData.value.forEach((item, index) => {
        pushData.push({
          title: `购买量 ≥${item.num}`,
          slotName: `wholePrice${index}`,
        });
      });
    }
    // 有重量的情况
    if (
      baseInfoForm.value.goodsType !== 'VIRTUAL_GOODS' &&
      baseInfoForm.value.salesModel !== 'WHOLESALE'
    ) {
      pushData.push({ title: '重量', slotName: 'weight' });
    }
    pushData.push(
      { title: '库存', slotName: 'quantity' },
      { title: '货号', slotName: 'sn' },
      { title: '图片', slotName: 'images' }
    );
    skuTableColumn.value = pushData;

    // 克隆所有渲染的数据
    if (skuInfo.value.length > 0) {
      // 存放最终结果
      const result = [] as any;
      skuIndex.value = 0;
      skuTableData.value = specIterator(
        result,
        skuInfo.value,
        skuTableData.value
      );
    }
  };
  // 渲染sku数据
  const renderGoodsDetailSku = (skuList: any) => {
    const skus = [] as any;
    let skusInfo = [] as any;
    skuList.forEach((e: any) => {
      const sku = {
        id: e.id,
        sn: e.sn,
        price: e.price,
        cost: e.cost,
        quantity: e.quantity,
        weight: e.weight,
      } as any;
      e.specList.forEach((u: any) => {
        if (u.specName === 'images') {
          sku.images = u.specImage;
        } else {
          sku[u.specName] = u.specValue;
          if (
            !skusInfo.some((s: any) => s.name === u.specName) &&
            !ignoreColumn.value.includes(u.specName)
          ) {
            skusInfo.push({
              name: u.specName,
              spec_id: u.specNameId,
              spec_values: [
                {
                  id: u.specValueId,
                  name: u.specName,
                  value: u.specValue || '',
                },
              ],
            });
          } else {
            skusInfo = skusInfo.map((sk: any) => {
              if (
                !sk.spec_values.some((s: any) => s.value === u.specValue) &&
                sk.name === u.specName
              ) {
                sk.spec_values.push({
                  id: u.specValueId,
                  name: u.specName,
                  value: u.specValue || '',
                });
              }
              if (!sk.spec_id && u.specName === 'specId') {
                sk.spec_id = u.specValue;
              }
              return sk;
            });
          }
        }
      });
      skus.push(sku);
    });
    skuInfo.value = skusInfo;
    skuTableData.value = skus;
    renderTableData(skus);
  };
  // 移除当前规格项，进行数据变化
  const handleCloseSkuItem = ($index: string | number, item: any) => {
    if ($index === 0 && skuInfo.value.length === 1) {
      skuInfo.value = [];
      skuTableData.value = [];
    } else {
      // 获取当前操作的规格项，在规格项数组中的位置（下标）
      let itemIndex = 0;
      Array.from(skuInfo.value).forEach((i: any, _index: number) => {
        if (i.name === item.name) {
          itemIndex = _index;
        }
      });
      if (itemIndex === skuInfo.value.length - 1) {
        // 如果当前为最后一个规格项，则按照下标按照最后一个规格项生成规则删除
        // 最后一个规格项生成规格数据规则： 如为最后一个规格项，则在规格列表每隔1个中删除n(n为最后一个规格项的规格值列表数量 - 1)个规格数据，生成一个规格数据
        // 除了当前操作的规格项的规格项列表，用于获取所有规格项的规格值列表总数
        const filterSkuInfo = skuInfo.value.filter(
          (i: any) => i.name !== item.name
        );
        let index = 1;
        let totalLength = 1;
        filterSkuInfo.forEach((skuInfo: any) => {
          totalLength *= skuInfo.spec_values.length;
        });
        // 去除第一个，因为第一个不需要生成新的规格数据
        item.spec_values.splice(0, 1);
        for (let i = 0; i < totalLength; i += 1) {
          // 移除对应的规格数据
          skuTableData.value.splice(index, item.spec_values.length);
          index += 1;
        }
      } else {
        // 当前规格项生成规格数据的时候，每次应该生成的条数
        let currentNum =
          skuInfo.value[skuInfo.value.length - 1].spec_values.length;
        for (let i = skuInfo.value.length - 2; i > itemIndex; i -= 1) {
          // 计算每次删除规格数据后移动的位置（计算规则为，以最后的规格项的规格值数量为基础，乘以其他规格项的规格值总数）
          currentNum *= skuInfo.value[i].spec_values.length;
        }
        // 移除对应规格数据的起始索引，起始位置为每次生成条数的下一位
        let beginIndex = currentNum + 1;

        const filterSkuInfo = skuInfo.value.filter(
          (i: any) => i.name !== item.name
        );
        let totalLength = 1;
        filterSkuInfo.forEach((skuInfo: any) => {
          totalLength *= skuInfo.spec_values.length;
        });
        for (let i = 0; i < totalLength; i += 1) {
          // 移除对应的规格数据，删除数量为 每次生成条数 * （当前规格项的规格值总数 - 1）
          skuTableData.value.splice(
            beginIndex,
            currentNum * (item.spec_values.length - 1)
          );
          beginIndex += currentNum;
        }
      }
      skuInfo.value.splice($index, 1);
      skuTableData.value = skuTableData.value.map((e: any) => {
        delete e[item.name];
        return e;
      });
    }
    renderTableData(skuTableData.value);
  };
  const changeSkuItem = (val: any) => {
    currentSkuItem.value = val;
  };
  // 获取焦点时，取得规格名对应规格项
  const changeSkuVals = (val: any, name: any) => {
    currentSkuVal.value = val.value;
    if (name) {
      skuData.value.forEach((e, index) => {
        if (e === name) {
          if (skuVal.value.length !== skuVals.value[index].length) {
            skuVal.value = skuVals.value[index];
          }
        }
      });
    }
  };
  // 编辑规格名
  const editSkuItem = (val: any, index: number, item: any) => {
    if (skuTableColumn.value.find((i) => i[val])) {
      Message.error('已存在相同规格项！');
      return;
    }
    // skuTableData.value = skuTableData.value.forEach((e)=>{
    //   e[val] = e[currentSkuItem.value];
    //     delete e[currentSkuItem.value];
    //     return e;
    // })

    currentSkuItem.value = val;
    renderTableData(skuTableData.value);
  };
  // 编辑规格值
  const skuValueChange = (val: any, index: number, item: any) => {
    if (skuTableData.value.find((i: any) => i[val.name] === val.value)) {
      Message.error('已存在相同规格值');
      return;
    }
    if (val.value === '') {
      Message.error('规格值不能为空');
      return;
    }
    lastEditSkuValue.value = val.value;
    const curVal = currentSkuVal.value;
    skuTableData.value = skuTableData.value.map((e: any) => {
      if (e[val.name] === curVal) {
        e[val.name] = val.value;
      }
      return e;
    });
    currentSkuVal.value = val.value;
    renderTableData(skuTableData.value);
  };

  const checkSkuVal = (val: any, skuIndex: any, space: any) => {
    if (val.value === '') {
      Message.error('规格值不能为空！');
      skuInfo.value[skuIndex] &&
        (skuInfo.value[skuIndex].spec_values = skuInfo.value[
          skuIndex
        ].spec_values.filter((i: any) => i.value !== ''));
      skuTableData.value = skuTableData.value.filter(
        (e: any) => e[space.name] !== lastEditSkuValue.value
      );
    }
  };
  // 移除当前规格值
  const handleCloseSkuValue = (item: any, index: number, spec: any) => {
    if (spec.spec_values.length <= 1) {
      Message.error('至少保留一个规格值！');
    }
    skuInfo.value.forEach((i: any) => {
      if (i.name === spec.name) {
        i.spec_values.splice(index, 1);
      }
    });
    skuTableData.value = skuTableData.value.filter(
      (e: any) => e[spec.name] !== item.value
    );
    baseInfoForm.value.regeneratorSkuFlag = true;
  };
  // 添加规格值的验证
  const validateEmpty = (params: any) => {
    let flag = true;
    params.forEach((item: any) => {
      if (!item.value) {
        Message.error('请必填规格项');
        flag = false;
      }
      return false; // 终止程序
    });
    return flag;
  };
  // 添加当前规格项的规格值
  const addSpec = ($index: number, item: any) => {
    if (validateEmpty(item.spec_values)) {
      if (item.spec_values.length >= 10) {
        Message.error('规格值不能大于10个！');
      }
      const beforeLength = item.spec_values.length;
      item.spec_values.push({
        name: item.name,
        value: '',
      });
      if (item.spec_values.length > 1) {
        let index = beforeLength;
        const filterSkuInfo = skuInfo.value.filter(
          (i: any) => i.name !== item.name
        );
        let totalLength = 1;
        filterSkuInfo.forEach((skuInfo: any) => {
          totalLength *= skuInfo.spec_values.length;
        });
        if ($index === 0) {
          index = 1;
          for (let i = 0; i < totalLength; i += 1) {
            const find = cloneObj(skuTableData.value[index - 1]) as any;
            find[item.name] = '';
            find.id = '';
            find.price && (find.price = '');
            find.sn && (find.sn = '');
            find.cost && (find.cost = '');
            find.quantity && (find.quantity = '');
            find.weight && (find.weight = '');

            skuTableData.value.splice(skuTableData.value.length, 0, find);
            index += 1;
          }
        } else {
          for (let i = 0; i < totalLength; i += 1) {
            const find = cloneObj(skuTableData.value[index - 1]) as any;
            find[item.name] = '';

            find.id = '';
            find.price && (find.price = '');
            find.sn && (find.sn = '');
            find.cost && (find.cost = '');
            find.quantity && (find.quantity = '');
            find.weight && (find.weight = '');

            skuTableData.value.splice(index, 0, find);
            index += $index === 0 ? beforeLength : beforeLength + 1;
          }
        }
      }
      baseInfoForm.value.regeneratorSkuFlag = true;
    }
  };
  // 添加规格项
  const addSkuItem = () => {
    if (skuInfo.value.length >= 5) {
      Message.error('规格项不能大于5个！');
    }
    if (Array.from(skuInfo.value).find((i: any) => i.name === '')) {
      Message.error('规格项不能为空！');
    }
    skuInfo.value.push({
      spec_values: [{ name: '', value: '' }],
      name: '',
    });
    renderTableData(skuTableData.value);
  };
  // 数据改变之后，抛出数据
  const updateSkuTable = (
    row: any,
    rowIndex: any,
    item: any,
    type = 'default'
  ) => {
    const indexs = rowIndex;
    baseInfoForm.value.regeneratorSkuFlag = true;
    // 进行自定义校验 判断是否是数字（小数也能通过）重量
    if (item === 'weight') {
      if (
        !/^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/.test(row[item]) ||
        parseInt(row[item], 10) < 0 ||
        parseInt(row[item], 10) > 99999999
      ) {
        // 校验未通过 加入错误存储列表中
        // validateError.value.push([indexs, item]);
        // validatatxt.value = '请输入0~99999999之间的数字值';
        Message.error('请输入0~99999999之间的数字值');
      }
    } else if (item === 'quantity') {
      if (
        !/^[0-9]\d*$/.test(row[item]) ||
        parseInt(row[item], 10) < 0 ||
        parseInt(row[item], 10) > 99999999
      ) {
        // 库存
        // validateError.value.push([indexs, item]);
        // validatatxt.value = '请输入0~99999999之间的整数';
        Message.error('请输入0~99999999之间的整数');
        return;
      }
    } else if (item === 'cost' || item === 'price') {
      if (
        !money.test(row[item]) ||
        parseInt(row[item], 10) < 0 ||
        parseInt(row[item], 10) > 99999999
      ) {
        // 成本价 价格
        // validateError.value.push([indexs, item]);
        // validatatxt.value = '请输入0~99999999之间的价格';
        Message.error('请输入0~99999999之间的价格');
      }
    }
    nextTick(() => {
      skuTableData.value[indexs][item] = row[item];
    });
  };
  // 将pc商品描述同步给移动端
  const promiseIntroEditor = () => {
    baseInfoForm.value.mobileIntro = JSON.parse(
      JSON.stringify(baseInfoForm.value.intro)
    );
  };
  // 更新sku图片
  const updateSkuPicture = (val: any) => {
    baseInfoForm.value.regeneratorSkuFlag = true;
    let selectedImage = skuTableData.value[val - 1];
    selectedImage = selectedSku.value;
  };
  const mouseOver = (v: any) => {
    showContent.value = true;
    listImages.value = v;
    if (listImages.value.images.length <= 0) {
      contentImage.value = '规格专属图片暂无';
      if (
        baseInfoForm.value &&
        baseInfoForm.value.goodsGalleryList &&
        baseInfoForm.value.goodsGalleryList.length
      ) {
        contentImage.value = '规格专属图片暂无';
        listImages.value.images = [baseInfoForm.value.goodsGalleryList[0]];
      }
    } else {
      contentImage.value = '当前规格专属图片';
    }
  };
  // 视频上传成功
  const handleSuccessGoodsVideo = (file: any) => {
    if (file.response.success) {
      file.url = file.response.result;
      baseInfoForm.value.goodsVideo = file.url;
    }
  };
  // 编辑sku图片
  const editSkuPicture = (row: any) => {
    // if (row.images && row.images.length > 0) {
    //     previewPicture.value = row.images[0].url;
    //   }
    selectedSku.value = { ...row };
    // selectedSku.value.images = row.images.map(item => {
    //   return {url: item};
    // });
    showSkuPicture.value = true;
  };
  // 清空规格项
  const handleClearSku = () => {
    skuInfo.value = [];
    skuTableData.value = [];
    renderTableData(skuTableData.value);
  };
  // 获取店内分类
  const getShopGoodsLabel = () => {
    getLabelData().then((res) => {
      if (res.data.success) {
        shopCategory.value = res.data.result;
      }
    });
  };
  // 从资源库导入图片
  const importOSS = () => {
    showOssManager.value = true;
  };
  // oss弹框确定
  const handleOss = () => {
    showOssManager.value = false;
  };
  const handleCancel = () => {
    showOssManager.value = false;
  };
  const changOssImage = (val: any) => {
    selectedSku.value.images = [];
    val.forEach((item: any) => {
      selectedSku.value.images.push({ url: item.url });
    });
  };
  // 批发型删除事件
  const handleDeleteWholesaleData = (index: number) => {
    wholesaleData.value.splice(index, 1);
    renderTableData(skuTableData.value);
  };
  // 批发型添加价格区间
  const handleAddWholesaleData = () => {
    if (
      wholesaleData.value.length === 1 &&
      (wholesaleData.value[0].price <= 0 || wholesaleData.value[0].num <= 0)
    ) {
      Message.error('请输入正确的销售规则');
    }
    if (wholesaleData.value.length < 3) {
      wholesaleData.value.push({
        price:
          Number(wholesaleData.value[wholesaleData.value.length - 1].price) -
          0.01,
        num:
          Number(wholesaleData.value[wholesaleData.value.length - 1].num) + 1,
        goodsId: goodsId.value,
      });
    }
    renderTableData(skuTableData.value);
  };
  // 店内分类选择
  const selectTree = (newSelectedKeys: any) => {};
  // 店内分类选中
  const changeSelect = (newCheckedKeys: any, event: any) => {
    if (newCheckedKeys.length > 100) {
      Message.error('选择了过多的店铺分类，请谨慎选择');
    }
    baseInfoForm.value.storeCategoryPath = newCheckedKeys;
  };
  /**
   * 选择参数
   * @paramsGroup 参数分组
   * @groupIndex 参数分组下标
   * @params 参数选项
   * @paramIndex 参数下标值
   * @value 参数选项值
   */
  const selectParams = (
    paramsGroup: any,
    groupIndex: number,
    params: any,
    paramsIndex: any,
    value: any
  ) => {
    if (!baseInfoForm.value.goodsParamsDTOList[groupIndex]) {
      baseInfoForm.value.goodsParamsDTOList[groupIndex] = {
        groupId: '',
        groupName: '',
        goodsParamsItemDTOList: [],
      };
    }
    // 赋予分组id、分组名称
    baseInfoForm.value.goodsParamsDTOList[groupIndex].groupId =
      paramsGroup.groupId;
    baseInfoForm.value.goodsParamsDTOList[groupIndex].groupName =
      paramsGroup.groupName;
    // 参数详细为空，则赋予
    if (
      !baseInfoForm.value.goodsParamsDTOList[groupIndex].goodsParamsItemDTOList[
        paramsIndex
      ]
    ) {
      baseInfoForm.value.goodsParamsDTOList[groupIndex].goodsParamsItemDTOList[
        paramsIndex
      ] = {
        paramName: '',
        paramValue: '',
        isIndex: '',
        // required: "",
        paramId: '',
        sort: '',
      };
    }
    baseInfoForm.value.goodsParamsDTOList[groupIndex].goodsParamsItemDTOList[
      paramsIndex
    ] = {
      paramName: params.paramName,
      paramValue: value,
      isIndex: params.isIndex,
      // required: params.required,
      paramId: params.id,
      sort: params.sort,
    };
  };
  // 根据当前分类ID查询商品包含的参数
  const getGoodsParams = () => {
    goodsParams.value = [];
    getCategoryParamsListDataSeller(categoryId.value).then((response) => {
      // if(!response || response.length <= 0){
      //   goodsParams.value= []
      // }
      goodsParams.value = response;
      // 展开选项卡
      Object.values(goodsParams.value).map((item: any) => {
        return paramsPanel.value.push(item.groupName);
      });
      if (baseInfoForm.value.goodsParamsDTOList) {
        // 已选值集合
        const paramsArr = [] as any;
        baseInfoForm.value.goodsParamsDTOList.forEach((group: any) => {
          group.goodsParamsItemDTOList.forEach((param: any) => {
            param.groupId = group.groupId;
            paramsArr.push(param);
          });
        });
        // 循环参数分组
        Object.values(goodsParams.value).forEach((paramsGroup: any) => {
          if (paramsGroup && paramsGroup.params) {
            paramsGroup.params.forEach((param: any) => {
              paramsArr.forEach((arr: any) => {
                if (param.paramName === arr.paramName) {
                  param.paramValue = arr.paramValue;
                }
              });
            });
          }
        });
      } else {
        baseInfoForm.value.goodsParamsDTOList = [];
      }
    });
  };
  const checkWholesaleNum = (index: number) => {
    if (wholesaleData.value[index].num < 0) {
      Message.error('购买数量必须大于0');
      wholesaleData.value[index].num = 0;
    }
    if (
      index > 0 &&
      wholesaleData.value[index - 1].num >= wholesaleData.value[index].num
    ) {
      Notification.info({
        title: '在批发模式的销售规则中',
        content: '下一个购买数量必须大于上一个购买数量',
        duration: 5000,
      });
      wholesaleData.value[index].num = wholesaleData.value[index - 1].num + 1;
    }
    renderTableData(skuTableData.value);
  };
  const checkWholesalePrice = (index: number) => {
    if (wholesaleData.value[index].price < 0) {
      Message.error('商品单价必须大于0');
      wholesaleData.value[index].price = 0;
    }
    if (
      index > 0 &&
      wholesaleData.value[index - 1].price <= wholesaleData.value[index].price
    ) {
      Notification.info({
        title: '在批发模式的销售规则中',
        content: '下一个商品单价必须小于上一个商品单价',
        duration: 5000,
      });
      wholesaleData.value[index].price =
        wholesaleData.value[index - 1].price - 0.01;
    }
    renderTableData(skuTableData.value);
  };
  // 根据分类id获取系统设置规格信息
  const skuInfoByCategory = (categoryId?: string | number) => {
    if (categoryId) {
      getGoodsSpecInfoSeller(categoryId).then((res: any) => {
        if (res.length) {
          res.forEach((e: any) => {
            skuData.value.push(e.specName);
            const vals = e.specValue ? e.specValue.split(',') : [];
            skuVals.value.push(Array.from(new Set(vals)));
          });
        }
      });
    }
  };
  // 上一步
  const pre = () => {
    // 商品分类传给父级
    emit('preChange', {
      categoryPath: baseInfoForm.value.categoryPath,
      categoryName: baseInfoForm.value.categoryName,
    });
    activestep.value = 1;
    // router.go(-1)
  };
  // 保存模板
  const SAVE_DRAFT_GOODS = () => {
    if (baseInfoForm.value.salesModel === 'WHOLESALE') {
      baseInfoForm.value.wholesaleList = wholesaleData.value;
    }
    saveDraftGoods(baseInfoForm).then((res) => {
      if (res.data.success) {
        Message.info('保存成功！');
        router.push({ name: 'draft-goods-list' });
      }
    });
  };
  // 保存为模板
  const saveToDraft = () => {
    baseInfoForm.value.skuList = skuTableData.value;
    // if(baseInfoForm.value.goodsGalleryFiles.length > 0){
    //   baseInfoForm.value.goodsGalleryList = baseInfoForm.value.goodsGalleryFiles.map((i) => i.url);
    // }
    baseInfoForm.value.categoryName = [];
    baseInfoForm.value.saveType = 'TEMPLATE';
    if (route.query.draftId) {
      baseInfoForm.value.id = route.query.draftId;
      modal.confirm({
        title: '当前模板已存在',
        content: '当前模板已存在，保存为新模板或替换原模板',
        okText: '保存新模板',
        cancelText: '替换旧模板',
        onOk: () => {
          delete baseInfoForm.value.id;
          SAVE_DRAFT_GOODS();
        },
        onCancel: () => {
          SAVE_DRAFT_GOODS();
        },
      });
    }
    modal.confirm({
      title: '保存模板',
      content: '是否确定保存',
      okText: '保存',
      closable: true,
      onOk: () => {
        SAVE_DRAFT_GOODS();
      },
    });
  };
  // 保存
  const save = async () => {
    const auth = await baseInfoFormRules.value?.validate();
    if (!auth) {
      if (baseInfoForm.value.salesModel === 'WHOLESALE') {
        for (let i = 0; i < wholesaleData.value.length; i += 1) {
          checkWholesaleNum(i);
          checkWholesalePrice(i);
          wholesaleData.value[i].goodsId = goodsId.value;
        }
        baseInfoForm.value.wholesaleList = wholesaleData.value;
      }
      baseInfoForm.value.goodsId = goodsId.value;
      const submit = JSON.parse(JSON.stringify(baseInfoForm.value));

      if (submit.storeCategoryPath) {
        submit.storeCategoryPath = submit.storeCategoryPath.join(',');
      }
      if (submit.goodsGalleryList && submit.goodsGalleryList.length <= 0) {
        Message.error('请上传商品图片');
        return false;
      }
      if (submit.templateId === '' || submit.templateId === null)
        submit.templateId = 0;
      const flag = false;
      const paramValue = '';
      if (flag) {
        Message.error(`${paramValue} 参数值不能为空`);
      }
      if (submit.goodsId === '') {
        delete submit.goodsId;
      }
      if (submit.mobileIntro && submit.mobileIntro.length) {
        submit.mobileIntro = submit.mobileIntro.toString();
      } else {
        submit.mobileIntro = '';
      }
      if (submit.intro && submit.intro.length) {
        submit.intro = submit.intro.toString();
      } else {
        submit.intro = '';
      }
      const skuInfoNames = skuInfo.value.map((n: any) => n.name);
      submit.skuList = [];
      skuTableData.value.forEach((sku: any) => {
        const skuCopy = {
          cost: sku.cost,
          price: sku.price,
          quantity: sku.quantity,
          sn: sku.sn,
          images: sku.images,
        } as any;
        if (sku.weight) {
          skuCopy.weight = sku.weight;
        }
        if (baseInfoForm.value.weight) {
          skuCopy.weight = baseInfoForm.value.weight;
        }
        if (sku.id) {
          skuCopy.id = sku.id;
        }
        //  eslint-disable-next-line
        for (const skuInfoName of skuInfoNames) {
          skuCopy[skuInfoName] = sku[skuInfoName];
        }
        submit.skuList.push(skuCopy);
      });
      // if(submit.goodsGalleryFiles.length > 0){
      //   submit.goodsGalleryList = submit.goodsGalleryFiles
      // }
      // 参数校验
      submit.release ? (submit.release = true) : (submit.release = false);
      submit.recommend ? (submit.recommend = true) : (submit.recommend = false);
      // 复制商品
      if (route.query.copyId) {
        goodsId.value = null;
        submit.id = null;
        submit.skuList = submit.skuList.map((item: any) => {
          delete item.id;
          return item;
        });
      }
      if (goodsId.value) {
        editGoods(goodsId.value, submit).then((res: any) => {
          if (res.data.success) {
            // router.go(-1);
            Message.success('商品修改成功！');
            router.push({ name: 'goods-list' });
          }
        });
      } else {
        createGoods(submit).then((res: any) => {
          if (res.data.success) {
            activestep.value = 3;
          }
        });
      }
    }
  };
  // 编辑时获取商品信息
  const goodData = async (id?: any, draftId?: any, copyId?: any) => {
    let response = {} as any;
    if (draftId) {
      response = await getDraftGoodsDetail(draftId);
    } else if (copyId) {
      response = await getGoods(copyId);
    } else {
      response = await getGoods(id);
      goodsId.value = response.data.result.id;
    }
    if (response.data.result.mobileIntro) {
      response.data.result.mobileIntro =
        response.data.result.mobileIntro.split(',');
    }
    if (response.data.result.intro) {
      response.data.result.intro = response.data.result.intro.split(',');
    }
    response.data.result.recommend
      ? (response.data.result.recommend = 1)
      : (response.data.result.recommend = 0);
    const data = { ...baseInfoForm.value, ...response.data.result };
    goodsFileList.value = response.data.result.goodsGalleryList
      ? [{ url: response.data.result.goodsGalleryList }]
      : [];
    baseInfoForm.value = data;
    if (props.firstData.goodsType) {
      baseInfoForm.value.goodsType = props.firstData.goodsType;
    }
    baseInfoForm.value.intro = baseInfoForm.value.intro
      ? baseInfoForm.value.intro
      : [];
    baseInfoForm.value.mobileIntro = baseInfoForm.value.mobileIntro
      ? baseInfoForm.value.mobileIntro
      : [];
    if (data.storeCategoryPath) {
      baseInfoForm.value.storeCategoryPath = data.storeCategoryPath.split(',');
    }
    baseInfoForm.value.release = 1; // 即使是被放入仓库，修改的时候也会显示会立即发布
    const category = response.data.result.categoryPath.split(',')[2];
    categoryId.value = category;
    // if(response.result.goodsGalleryList && response.result.goodsGalleryList.length > 0){
    //   baseInfoForm.value.goodsGalleryFiles = response.result.goodsGalleryList.map((i) =>
    //     {
    //       return { url: i };
    //     });
    // }
    if (
      response.data.result.wholesaleList &&
      response.data.result.wholesaleList.length > 0
    ) {
      wholesaleData.value = response.data.result.wholesaleList;
    }
    if (response.data.result.salesModel === 'WHOLESALE') {
      baseInfoForm.value.weight = response.data.result.skuList[0].weight;
    }
    skuInfoByCategory(categoryId.value);
    renderGoodsDetailSku(response.data.result.skuList);
    // 查询品牌列表
    getGoodsBrandList();
    // 获取当前店铺分类
    getShopGoodsLabel();
    // 获取商品单位
    goodsUnit();
    if (props.firstData.category) {
      const cateId = [] as any;
      baseInfoForm.value.categoryName = [];
      props.firstData.category.forEach((cate: any) => {
        baseInfoForm.value.categoryName.push(cate.name);
        cateId.push(cate.id);
      });
      const category = cateId[2];
      categoryId.value = category;
      // categoryId.value = cateId[2];
      baseInfoForm.value.brandId = null;
      baseInfoForm.value.brandName = null;
      getGoodsBrandList();
      baseInfoForm.value.categoryPath = cateId.toString();
    }
    props.firstData.goodsType &&
      (baseInfoForm.value.goodsType = props.firstData.value.goodsType);
    // 查询商品参数
    getGoodsParams();
  };
  onMounted(() => {
    // 获取物流模板
    getShipTemplate().then((res) => {
      logisticsTemplate.value = res.data.result;
    });
    if (route.query.id || route.query.draftId || route.query.copyId) {
      // 编辑商品、模板
      goodData(route.query.id, route.query.draftId, route.query.copyId);
    } else {
      const a = props.firstData;
      // 新增商品、模板
      if (props.firstData.tempId) {
        // 选择模板
        goodData('', props.firstData.tempId);
      } else {
        const cateId = [] as any;
        props.firstData.category.forEach((cate: any) => {
          baseInfoForm.value.categoryName.push(cate.name);
          cateId.push(cate.id);
        });
        const category = cateId[2];
        categoryId.value = category;
        baseInfoForm.value.categoryPath = cateId.toString();
        baseInfoForm.value.goodsType = props.firstData.goodsType;
        // 获取商品分类下 商品参数信息
        getGoodsParams();
        // 查询品牌列表
        getGoodsBrandList();
        // 查询分类绑定的规格信息
        skuInfoByCategory();
        // 获取商品单位
        goodsUnit();
        // 获取当前店铺分类
        getShopGoodsLabel();
      }
    }
  });
</script>

<style lang="less" scoped>
  @import './addGoods.less';
  :deep(.arco-select-view-single) {
    width: 320px;
  }
  :deep(.arco-input-wrapper) {
    max-width: 320px;
  }
  :deep(.arco-textarea-wrapper) {
    max-width: 320px;
  }
  .actions {
    display: flex;
    align-items: center;
    margin-left: 70px;
  }
  .action {
    padding: 5px 4px;
    font-size: 14px;
    // margin-left: 12px;
    border-radius: 2px;
    line-height: 1;
    cursor: pointer;
  }
  // .action:first-child {
  //   margin-left: 80px;
  // }

  .action:hover {
    background: rgba(0, 0, 0, 0.5);
  }
  .import-oss {
    margin-bottom: 10px;
    text-align: right;
    color: red;
    cursor: pointer;
  }
  .video {
    width: 200px;
  }

  .footer {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .mobile-intro {
    display: flex;
    > div:nth-of-type(2) {
      width: 100%;
    }
    > div:nth-of-type(1) {
      flex: 1;
    }
  }
  .mobile-effect {
    box-sizing: border-box;
    margin-right: 20px;
    border: 2px solid #f1f2f3;
    height: 570px;
    .title {
      align-items: center;
      background: #f9f9fa;
      border-radius: 4px 4px 0 0;
      color: #85878a;
      display: flex;
      font-size: 12px;
      height: 32px;
      line-height: 20px;
      padding: 0 12px;
    }
    .content {
      width: 310px;
      height: 534px;
      /*padding: 0 14px;*/
      overflow-y: scroll;
      img {
        width: 100%;
      }
    }
    .text {
      line-height: 500px;
      text-align: center;
      color: #999999;
    }
  }

  .goods-sku-images-upload {
    display: flex;
    justify-content: center;
    align-items: center;
    min-width: 80px;
    height: 80px;
    margin-bottom: 0;
    color: #4e5969;
    text-align: center;
    background: #f2f3f5;
    border: 1px dashed #e5e6eb;
    border-radius: 2px;
    transition: all 0.1s cubic-bezier(0, 0, 1, 1);
  }
</style>
